package cn.com.ejiakanghu.config;


import cn.com.ejiakanghu.core.exceptions.BizException;
import cn.com.ejiakanghu.core.utils.RespUtil;
import cn.com.ejiakanghu.core.vo.BaseResult;
import cn.com.ejiakanghu.service.OrderManager;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;


@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 获取报错的堆栈信息
     * @return
     */
    private static void generateTag(Throwable throwable) {
        StringWriter stringWriter=new StringWriter();
        PrintWriter printWriter=new PrintWriter(stringWriter);

        try {
            throwable.printStackTrace(printWriter);
            logger.error("错误日志:{}",stringWriter);
        }finally {
            printWriter.close();
        }
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public Object serviceExceptionHandler(BizException e) {
        logger.error("错误：{}",e);
        return RespUtil.fail(500, e.getMessage());
    }

    /**
     * 异常处理  通用直接返回服务异常
     */
    @ExceptionHandler(Exception.class)
    public BaseResult exceptionHandler(HttpServletRequest request, Exception e) {
        //TODO 打印异常请求信息
        logger.error("错误：{}",e);
        generateTag(e);
        return RespUtil.fail();
    }
}
